﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using SqlSugar;
using System.Buffers;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Security.Claims;
using Zhao.Common.EnumEntity;
using Zhao.Common.Helper;
using Zhao.IServer.Management_Arena;
using Zhao.IServer.User;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Management_Arena
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class VenueApplicationsController : ControllerBase
    {
        private readonly IVenueApplicationsServer _applicationsServer;
        private readonly IAdminServer _adminServer;


        public VenueApplicationsController(IVenueApplicationsServer applicationsServer, IAdminServer adminServer)
        {
            this._applicationsServer = applicationsServer;
            this._adminServer = adminServer;    
        }


        /// <summary>
        /// 获取入住球馆详情信息
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageindex:int}/{pageSize:int}")]
        [Route("{pageindex:int}/{pageSize:int}/{stasus:int}")]
        [Route("{pageindex:int}/{pageSize:int}/{searchaString}")]
        [Route("{pageindex:int}/{pageSize:int}/{searchaString}/{stasus:int}")]
        public async Task<JsonResult> GetVenuesApplicationsPageInfo(int pageindex = 1, int pageSize = 10, string? searchaString = null, int? stasus = -1)
        {
            var result = new PageModel<VenueApplicationDTO>();

            Expressionable<VenueApplications, Admin, Users, Area, Area, Area> expression = new Expressionable<VenueApplications, Admin, Users, Area,Area,Area>();

            expression.AndIF(!searchaString.IsNullOrWhiteSpace(), ((a, b, c, d, e, f) => a.VenueName.Contains(searchaString) || a.Address.Contains(searchaString) || a.ContactPhone.Contains(searchaString) || c.Username.Contains(searchaString) || d.Name.Contains(searchaString) || e.Name.Contains(searchaString) || f.Name.Contains(searchaString)));

            expression.AndIF(stasus != -1, (a, b, c, d, e, f) => a.Status.Equals(stasus));

            result = await _applicationsServer.VenueApplicationsQuery(expression.ToExpression(), pageindex, pageSize);

            if (result != null)
            {
                return new JsonResult(result);
            }

            return new JsonResult(result);
        }


        /// <summary>
        /// 审核入驻状态
        /// </summary>
        /// <param name="requestDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> ReviewVenues([FromBody] ReviewRequestDto requestDto)
        {
            var result = new ApiResult
            {
                Success = false,
                Message = "操作失败"
            };

            // 1. 参数验证
            if (!ModelState.IsValid)
            {
                result.Message = "参数校验失败";
                return new JsonResult(result);
            }

            // 2. 获取当前操作用户ID
            var currentRoleId = User.FindFirstValue(ClaimTypes.Role);
            var userIds = User.FindFirstValue(ClaimTypes.Sid);

            if (currentRoleId.IsNullOrWhiteSpace() || !int.TryParse(currentRoleId, out var roleId)
                || userIds.IsNullOrWhiteSpace() || !int.TryParse(userIds, out var userId))
            {
                result.Message = "未获取到有效用户信息";
                return new JsonResult(result);
            }

            //查询当前管理员是否存在 要不然直接存进数据库会有操作风险
           var admin= await _adminServer.QueryAsync(x => x.Id == userId);

            if (roleId != (int)RoleEnum.Admin|| admin==null)
            {
                result.Message = "没有操作权限";
                return new JsonResult(result);
            }

            // 3. 验证申请记录是否存在
            var application = await _applicationsServer.QueryAsync(a => a.ApplicationID == requestDto.ApplicationID);

            if (application == null)
            {
                result.Message = "申请记录不存在";
                return new JsonResult(result);
            }

            // 5. 检查状态是否重复
            if (application.Status == requestDto.Status)
            {
                result.Message = "申请状态未发生变化";
                return new JsonResult(result);
            }

            // 6. 拒绝时必须填写意见
            if (requestDto.Status == 5 && requestDto.ApprovalOpinion.IsNullOrWhiteSpace())
            {
                result.Message = "拒绝申请必须填写审核意见";
                return new JsonResult(result);
            }

            application.Status= requestDto.Status;
            application.ApprovalOpinion= requestDto.ApprovalOpinion;

            result =await _applicationsServer.ProcessReviewAsync(application, admin.Id);

            return new JsonResult(result);
        }

    }
}
